package com.xrit.controller;

import com.aliyuncs.exceptions.ClientException;
import com.xrit.constant.MessageConstant;
import com.xrit.constant.RedisMessageConstant;
import com.xrit.pojo.SetMeal;
import com.xrit.result.Result;
import com.xrit.utils.QiNiuUtils;
import com.xrit.utils.SMSUtils;
import com.xrit.utils.ValidateCodeUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import redis.clients.jedis.JedisPool;

/**
 * 发送验证码
 */
@RestController
@RequestMapping("/validateCode")
public class ValidateCodeController {

    @Autowired
    private JedisPool jedisPool;

    @RequestMapping("/send4Order")
    public Result send4Order(String telephone){
        //为了保证唯一性：key = 手机号码_001
        String key=telephone+"_"+ RedisMessageConstant.SENDTYPE_ORDER;
        //在发送验证码之前，首先检测验证码是否已经存在
        String codeInRedis = jedisPool.getResource().get(key);
        if (StringUtils.isEmpty(codeInRedis)){
            //不存在
            //1.生成验证码
            String code = ValidateCodeUtils.generateValidateCode4String(4);
            //2.发送验证码(暂时无法实现)
        /*try {
            SMSUtils.sendShortMessage(SMSUtils.VALIDATE_CODE,telephone,null);
        } catch (ClientException e) {
            e.printStackTrace();
            return new Result(false, MessageConstant.SEND_VALIDATECODE_FAIL);
        }*/
            //3.保存验证码(设置有效时期) expire key second
//            jedisPool.getResource().setex(key,40,code);
            jedisPool.getResource().setex(key,40,"6666");
            return new Result(true, MessageConstant.SEND_VALIDATECODE_SUCCESS);
        }
        //存在
        return new Result(false, "验证码仍有效，请勿重复发送验证码!");
    }
}
